package server.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.DriverManager;
import server.model.players.Client;
import server.model.players.Player;
import server.model.players.PlayerHandler;
/**
 * MySQL Class
 * @author _iRamie'
 * Includes a few functions for various purposes, such as Voting Checks and Donation system checks.
 * Must configure MySql to work it, if you cant just comment it out on Client Class and Commands Class
 */

public class MysqlManager {

	/** MySQL Connection */
	public static Connection conn = null;
	public static Statement statement = null;
	public static ResultSet results = null;
	

	/**
	 * Creates a Connection to the MySQL Database
	 */
	public synchronized static void createKillDeathConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
				conn = DriverManager.getConnection("jdbc:mysql://factor-zero.net/factorze_kdr", "factorze_kdr", "tyler456");
			statement = conn.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public synchronized static void destroyConnection() {
		try {
			statement.close();
			conn.close();
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}
	
	public synchronized static ResultSet query(String s) throws SQLException {
		try {
			if (s.toLowerCase().startsWith("select")) {
				ResultSet rs = statement.executeQuery(s);
				return rs;
			} else {
				statement.executeUpdate(s);
			}
			return null;
		} catch (Exception e) {
			destroyConnection();
			createKillDeathConnection();
			//e.printStackTrace();
		}
		return null;
	}
	
	/****
		* Save Character Files in SQL Table
		* @param clientToSave The session that saves their stats
		* @return The flag true if successful
		*
		**/
		
	public static boolean savePlayerKills(Client clientToSave) {
		try {
			query("DELETE FROM `ratio` WHERE playerName = '"+clientToSave.playerName+"';");
			query("INSERT INTO `ratio` (`playerName`,`Kills`,`Deaths`) VALUES ('"+clientToSave.playerName+"',"+clientToSave.KC+","+clientToSave.DC+");");
				} catch (Exception e) {
			//e.printStackTrace();
			return false;
		}
		return true;
	}
		
	
}